<template>
  <div class="experience-detail-page">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <div class="flex flex-col space-y-4">
          <!-- 面包屑导航 -->
          <el-breadcrumb separator="/" class="text-sm">
            <el-breadcrumb-item :to="{ path: '/experiences' }"
              >特色体验</el-breadcrumb-item
            >
            <el-breadcrumb-item>{{
              experienceDetail.title
            }}</el-breadcrumb-item>
          </el-breadcrumb>

          <!-- 标题和操作按钮 -->
          <div class="flex items-center justify-between">
            <h1
              class="text-2xl font-bold text-gray-900 dark:text-white line-clamp-1 flex-1 mr-4"
            >
              {{ experienceDetail.title }}
            </h1>
            <div class="flex items-center gap-3">
              <el-button-group>
                <el-button
                  type="primary"
                  plain
                  :icon="Share"
                  @click="handleShare"
                  >分享</el-button
                >
                <el-button
                  :type="experienceDetail.isFavorited ? 'primary' : 'default'"
                  plain
                  :icon="Star"
                  @click="handleFavorite"
                >
                  {{ experienceDetail.isFavorited ? "已收藏" : "收藏" }}
                </el-button>
              </el-button-group>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧主要内容区 -->
        <div class="flex-1">
          <!-- 体验内容 -->
          <div
            class="experience-content bg-white dark:bg-gray-800 rounded-lg shadow-sm"
          >
            <!-- 体验状态和基本信息 -->
            <div class="border-b border-gray-100 dark:border-gray-700 p-6">
              <div class="flex items-center gap-6">
                <el-tag
                  :type="
                    experienceDetail.status === 'booking'
                      ? 'success'
                      : 'warning'
                  "
                  effect="light"
                  size="large"
                >
                  {{
                    experienceDetail.status === "booking"
                      ? "可预订"
                      : "名额告罄"
                  }}
                </el-tag>
                <div
                  class="flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400"
                >
                  <span class="flex items-center">
                    <el-icon class="mr-1"><Timer /></el-icon>
                    {{ experienceDetail.duration }}
                  </span>
                  <span class="flex items-center">
                    <el-icon class="mr-1"><User /></el-icon>
                    限{{ experienceDetail.maxParticipants }}人
                  </span>
                  <span class="flex items-center">
                    <el-icon class="mr-1"><View /></el-icon>
                    {{ formatNumber(experienceDetail.views) }}次浏览
                  </span>
                </div>
                <div class="flex-1"></div>
                <div
                  class="text-2xl font-bold text-primary-600 dark:text-primary-400"
                >
                  ¥{{ experienceDetail.price }}
                  <span
                    class="text-sm font-normal text-gray-500 dark:text-gray-400"
                    >起</span
                  >
                </div>
              </div>
            </div>

            <!-- 主图轮播 -->
            <div class="p-6">
              <el-carousel
                :height="'400px'"
                :autoplay="true"
                indicator-position="outside"
                class="rounded-lg overflow-hidden"
              >
                <el-carousel-item
                  v-for="image in experienceDetail.images"
                  :key="image"
                >
                  <el-image
                    :src="image"
                    fit="cover"
                    class="w-full h-full"
                    :preview-src-list="experienceDetail.images"
                  />
                </el-carousel-item>
              </el-carousel>
            </div>

            <!-- 体验详情 -->
            <div class="p-6">
              <div class="experience-sections space-y-8">
                <!-- 体验介绍 -->
                <div class="section-item">
                  <h2
                    class="flex items-center text-xl font-bold text-gray-900 dark:text-white mb-4"
                  >
                    <el-icon class="mr-2 text-primary-500"
                      ><InfoFilled
                    /></el-icon>
                    体验介绍
                  </h2>
                  <div class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-6">
                    <p class="text-gray-700 dark:text-gray-300 leading-relaxed">
                      {{ parsedContent.introduction || '暂无体验介绍' }}
                    </p>
                  </div>
                </div>

                <!-- 体验流程 -->
                <div class="section-item">
                  <h2
                    class="flex items-center text-xl font-bold text-gray-900 dark:text-white mb-4"
                  >
                    <el-icon class="mr-2 text-primary-500"><Timer /></el-icon>
                    体验流程
                  </h2>
                  <div class="flow-steps space-y-4">
                    <div
                      v-for="(step, index) in parsedContent.flowSteps"
                      :key="index"
                      class="step-item flex items-start bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4"
                    >
                      <div
                        class="step-number flex-shrink-0 w-8 h-8 bg-primary-500 text-white rounded-full flex items-center justify-center mr-4"
                      >
                        {{ index + 1 }}
                      </div>
                      <div class="flex items-center justify-between flex-1">
                        <span class="text-gray-700 dark:text-gray-300"
                          >{{ step }}</span
                        >
                        <span
                          v-if="stepDurations[index]"
                          class="text-primary-500 dark:text-primary-400 font-medium"
                          >{{ stepDurations[index] }}</span
                        >
                      </div>
                    </div>
                    
                    <!-- 如果没有流程步骤则显示提示 -->
                    <div 
                      v-if="!parsedContent.flowSteps || parsedContent.flowSteps.length === 0"
                      class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-6"
                    >
                      <p class="text-gray-500 dark:text-gray-400 text-center">暂无体验流程信息</p>
                    </div>
                  </div>
                </div>

                <!-- 包含服务 -->
                <div class="section-item">
                  <h2
                    class="flex items-center text-xl font-bold text-gray-900 dark:text-white mb-4"
                  >
                    <el-icon class="mr-2 text-primary-500"><Service /></el-icon>
                    包含服务
                  </h2>
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div
                      v-for="(service, index) in defaultServices[experienceDetail.category_id] || defaultServices.default"
                      :key="index"
                      class="service-item flex items-center bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4"
                    >
                      <el-icon class="text-primary-500 text-xl mr-3"
                        ><component :is="service.icon" /></el-icon>
                      <span class="text-gray-700 dark:text-gray-300"
                        >{{ service.name }}</span
                      >
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 体验须知 -->
            <div class="border-t border-gray-100 dark:border-gray-700 p-6">
              <h2 class="text-xl font-bold text-gray-900 dark:text-white mb-4">
                体验须知
              </h2>
              <div class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-6">
                <ul v-if="experienceDetail.notices"
                    class="list-disc list-inside text-gray-600 dark:text-gray-400 space-y-2">
                  <li v-for="(item, index) in noticesList" :key="index">{{ item }}</li>
                </ul>
                <p v-else class="text-gray-500 dark:text-gray-400 text-center">暂无体验须知信息</p>
              </div>
            </div>

            <!-- 用户评价 -->
            <div class="border-t border-gray-100 dark:border-gray-700 p-6">
              <div class="flex items-center justify-between mb-6">
                <h2 class="text-xl font-bold text-gray-900 dark:text-white">
                  用户评价
                </h2>
                <div class="flex items-center gap-4">
                  <div
                    class="text-3xl font-bold text-primary-600 dark:text-primary-400"
                  >
                    {{ experienceDetail.rating }}
                  </div>
                  <div>
                    <el-rate
                      v-model="experienceDetail.rating"
                      disabled
                      :max="5"
                      allow-half
                      :colors="['#ffd21e', '#ffd21e', '#ffd21e']"
                      :void-icon="Star"
                      :void-color="'rgba(128,128,128,0.4)'"
                      show-score
                      :decimal-place="1"
                      class="mb-1"
                    />
                    <div class="text-sm text-gray-500 dark:text-gray-400">
                      {{ experienceDetail.reviewCount }}条评价
                    </div>
                  </div>
                </div>
              </div>

              <!-- 评价列表 -->
              <div class="space-y-6">
                <div
                  v-for="review in displayedReviews"
                  :key="review.id"
                  class="review-item"
                >
                  <div class="flex items-start gap-4">
                    <el-avatar :size="40" :src="review.user.avatar">
                      {{ review.user.name.substring(0, 1) }}
                    </el-avatar>
                    <div class="flex-1">
                      <div class="flex items-center justify-between mb-2">
                        <div class="user-info">
                          <span
                            class="font-medium text-gray-900 dark:text-white"
                          >
                            {{ review.user.name }}
                          </span>
                          <span
                            class="text-sm text-gray-500 dark:text-gray-400 ml-2"
                          >
                            {{ formatTime(review.time) }}
                          </span>
                        </div>
                        <el-rate
                          v-model="review.rating"
                          disabled
                          :max="5"
                          class="scale-90"
                        />
                      </div>
                      <p class="text-gray-600 dark:text-gray-300 mb-2">
                        {{ review.content }}
                      </p>
                      <div class="flex flex-wrap gap-2">
                        <el-image
                          v-for="(image, index) in review.images"
                          :key="index"
                          :src="image"
                          class="w-20 h-20 rounded object-cover cursor-pointer"
                          :preview-src-list="review.images"
                        />
                      </div>
                      <div v-if="review.reply" class="review-reply mt-3 p-3 bg-gray-50 dark:bg-gray-700 rounded">
                        <div class="text-sm font-medium mb-1">主办方回复：</div>
                        <div class="text-sm text-gray-600 dark:text-gray-400">{{ review.reply }}</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 加载更多 -->
              <div v-if="hasMoreReviews" class="flex justify-center mt-8">
                <el-button text @click="loadMoreReviews">
                  加载更多评价
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar lg:w-80 flex-shrink-0">
          <!-- 主办方信息 -->
          <div
            class="host-info bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6"
          >
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
              主办方信息
            </h3>
            <div class="flex items-center gap-4 mb-4">
              <el-avatar :size="64" :src="experienceDetail.host.avatar" />
              <div>
                <h4 class="text-lg font-medium text-gray-900 dark:text-white">
                  {{ experienceDetail.host.name }}
                </h4>
                <p class="text-sm text-gray-500 dark:text-gray-400">
                  {{ experienceDetail.host.title }}
                </p>
              </div>
            </div>
            <p class="text-gray-600 dark:text-gray-400 text-sm mb-4">
              {{ experienceDetail.host.description }}
            </p>
            <div class="host-stats grid grid-cols-3 gap-4 text-center">
              <div class="stat-item">
                <div class="text-lg font-bold text-gray-900 dark:text-white">
                  {{ experienceDetail.host.experienceCount }}
                </div>
                <div class="text-sm text-gray-500 dark:text-gray-400">
                  体验项目
                </div>
              </div>
              <div class="stat-item">
                <div class="text-lg font-bold text-gray-900 dark:text-white">
                  {{ experienceDetail.host.participantCount }}
                </div>
                <div class="text-sm text-gray-500 dark:text-gray-400">
                  服务人次
                </div>
              </div>
              <div class="stat-item">
                <div class="text-lg font-bold text-gray-900 dark:text-white">
                  {{ experienceDetail.host.rating }}
                </div>
                <div class="text-sm text-gray-500 dark:text-gray-400">
                  综合评分
                </div>
              </div>
            </div>
          </div>

          <!-- 预订日历 -->
          <div
            class="booking-calendar bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6"
          >
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
              选择体验日期
            </h3>
            <div class="date-picker-wrapper">
              <el-date-picker
                v-model="selectedDate"
                type="date"
                :disabled-date="disabledDate"
                :shortcuts="dateShortcuts"
                placeholder="选择体验日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                class="w-full"
                size="large"
              />
              <div class="mt-4 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <div class="flex items-center justify-between mb-2">
                  <span class="text-gray-600 dark:text-gray-400">已选日期</span>
                  <span
                    class="text-primary-600 dark:text-primary-400 font-medium"
                  >
                    {{
                      selectedDate ? formatSelectedDate(selectedDate) : "未选择"
                    }}
                  </span>
                </div>
                <div class="flex items-center justify-between">
                  <span class="text-gray-600 dark:text-gray-400">剩余名额</span>
                  <span
                    class="text-primary-600 dark:text-primary-400 font-medium"
                  >
                    {{ selectedDate ? getAvailableSpots(selectedDate) : "-" }}
                    个
                  </span>
                </div>
              </div>
            </div>
            <el-button
              type="primary"
              class="w-full mt-4"
              size="large"
              :disabled="!selectedDate || getAvailableSpots(selectedDate) <= 0"
              @click="handleBook"
            >
              {{
                !selectedDate
                  ? "请选择日期"
                  : getAvailableSpots(selectedDate) <= 0
                    ? "名额已满"
                    : "立即预订"
              }}
            </el-button>
          </div>

          <!-- 体验地点 -->
          <div
            class="location-info bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6"
          >
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
              体验地点
            </h3>
            <p class="text-gray-600 dark:text-gray-400 mb-4">
              {{ experienceDetail.location.address }}
            </p>
            <div ref="mapContainer" class="map-container h-48 rounded-lg overflow-hidden mb-4">
              <!-- 地图组件 -->
            </div>
            <div class="text-sm text-gray-600 dark:text-gray-400">
              <p class="flex items-center mb-2">
                <el-icon class="mr-2"><Location /></el-icon>
                <span>{{ experienceDetail.location.address }}</span>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分享弹窗 -->
    <el-dialog
      v-model="showShareDialog"
      title="分享体验"
      width="360px"
      align-center
    >
      <div class="share-options grid grid-cols-4 gap-4">
        <div
          v-for="platform in sharePlatforms"
          :key="platform.name"
          class="share-item flex flex-col items-center cursor-pointer hover:text-primary-600 transition-colors"
          @click="handleShareTo(platform)"
        >
          <el-icon :size="24" class="mb-2">
            <component :is="platform.icon" />
          </el-icon>
          <span class="text-sm">{{ platform.label }}</span>
        </div>
      </div>
      <div class="mt-6">
        <div class="flex items-center bg-gray-50 dark:bg-gray-700 rounded p-2">
          <input
            type="text"
            :value="generateShareUrl"
            class="flex-1 bg-transparent border-none outline-none text-sm"
            readonly
          />
          <el-button type="primary" link @click="copyShareUrl">
            复制链接
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  Timer,
  User,
  View,
  Star,
  Share,
  Location,
  CopyDocument,
  Wechat,
  Weibo,
  InfoFilled,
  Service,
  Tools,
  Finished,
  Van,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import service from "@/api/axios";

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const showShareDialog = ref(false);
const selectedDate = ref(new Date());
const hasMoreReviews = ref(true);
const reviewPage = ref(1);
const reviewSize = ref(5);

// 高德地图相关
const mapContainer = ref(null);
let map = null;
const mapKey = "ac63e78c8bfb172aac3c5be005a25f28"; // 高德地图Key
const securityJsCode = "bddeaa4d8587f8b446342a53ee0d4994"; // 高德地图安全密钥
const mapLoaded = ref(false);

// 设置高德地图安全密钥配置
if (typeof window !== 'undefined') {
  window._AMapSecurityConfig = {
    securityJsCode: securityJsCode
  };
}

// 测试评价数据
const testReviews = [
  {
    id: 1,
    user: {
      name: "文化爱好者",
      avatar: "/images/avatars/user1.jpg",
    },
    rating: 5,
    time: "2024-04-15 14:30:00",
    content: "非常棒的体验！主办方教学很细心，让我这个零基础的人也能制作出满意的作品。整个过程很轻松愉快，强烈推荐！",
    images: ["/images/reviews/review1.jpg", "/images/reviews/review2.jpg"],
    reply: "感谢您的好评！我们一直致力于为每位参与者提供专业而愉快的体验，希望能再次见到您。"
  },
  {
    id: 2,
    user: {
      name: "小李游记",
      avatar: "/images/avatars/user2.jpg",
    },
    rating: 4.5,
    time: "2024-04-03 09:15:00",
    content: "活动很棒，学到了很多传统技艺知识。教学过程生动有趣，氛围很好。场地宽敞干净，工具齐全。唯一遗憾的是时间有点短，希望能更深入学习。",
    images: ["/images/reviews/review3.jpg"],
    reply: ""
  },
  {
    id: 3,
    user: {
      name: "旅行探索家",
      avatar: "/images/avatars/user3.jpg",
    },
    rating: 4,
    time: "2024-03-25 16:45:00",
    content: "这次体验给我留下了深刻印象，了解了当地传统工艺的历史和工艺流程。主办方很热情，讲解详细，整个过程很愉快。会推荐给朋友们。",
    images: [],
    reply: "谢谢您的评价！传统工艺的传承需要更多人的参与和了解，期待您的再次光临。"
  }
];

// 体验详情数据（默认测试数据）
const experienceDetail = ref({
  id: 1,
  title: "贵港陶艺制作体验",
  status: "booking",
  duration: "2小时",
  maxParticipants: 10,
  views: 12580,
  price: 128,
  rating: 4.8,
  reviewCount: 258,
  isFavorited: false,
  images: [
    "/images/experiences/pottery1.jpg",
    "/images/experiences/pottery2.jpg",
    "/images/experiences/pottery3.jpg",
  ],
  content: `
    <h2>体验介绍</h2>
    <p>跟随陶艺大师学习传统陶艺技艺，创作专属作品。在专业陶艺师的指导下，您将了解陶艺的基本知识，学习拉坯、捏塑等技巧，并创作出属于自己的陶艺作品。</p>
    <h2>体验流程</h2>
    <ol>
      <li>陶艺基础知识讲解（15分钟）</li>
      <li>拉坯技巧演示（30分钟）</li>
      <li>学员实践创作（60分钟）</li>
      <li>作品修饰完善（15分钟）</li>
    </ol>
    <h2>包含服务</h2>
    <ul>
      <li>专业陶艺师全程指导</li>
      <li>陶艺工具和材料使用</li>
      <li>作品烧制服务</li>
      <li>成品邮寄服务</li>
    </ul>
  `,
  host: {
    name: "张师傅",
    title: "陶艺非遗传承人",
    avatar: "/images/avatars/host1.jpg",
    description:
      "从事陶艺创作20余年，荣获多项非物质文化遗产传承人称号。擅长传统陶艺技法，致力于推广陶艺文化。",
    experienceCount: 5,
    participantCount: 1280,
    rating: 4.9,
  },
  location: {
    address: "贵港市港北区文化创意园区A栋101",
    latitude: 23.1167,
    longitude: 109.5978,
  },
  reviews: [],
});

// 显示的评价列表，如果没有真实数据则使用测试数据
const displayedReviews = computed(() => {
  if (experienceDetail.value.reviews && experienceDetail.value.reviews.length > 0) {
    return experienceDetail.value.reviews;
  }
  return testReviews;
});

// 分享平台
const sharePlatforms = [
  { name: "weixin", icon: "Wechat", label: "微信" },
  { name: "weibo", icon: "Weibo", label: "微博" },
  { name: "qq", icon: "ChatDotRound", label: "QQ" },
  { name: "copy", icon: "CopyDocument", label: "复制链接" },
];

// 生成分享链接
const generateShareUrl = computed(() => {
  return `${window.location.origin}/experiences/${experienceDetail.value.id}`;
});

// 解析内容文本，提取介绍和流程信息
const parsedContent = computed(() => {
  const content = experienceDetail.value.content || '';
  const result = {
    introduction: '',
    flowSteps: []
  };
  
  // 提取体验介绍部分
  const introMatch = content.match(/体验介绍[:：](.*?)(?=体验流程[:：]|$)/s);
  if (introMatch && introMatch[1]) {
    result.introduction = introMatch[1].trim();
  }
  
  // 提取体验流程部分
  const flowMatch = content.match(/体验流程[:：](.*?)(?=$)/s);
  if (flowMatch && flowMatch[1]) {
    // 根据顿号、逗号或句号分割流程步骤
    result.flowSteps = flowMatch[1].split(/[、，,。.]/)
      .map(step => step.trim())
      .filter(step => step.length > 0);
  }
  
  return result;
});

// 模拟每个步骤的时间（实际项目中可从后端获取或设置默认值）
const stepDurations = computed(() => {
  const durations = ['15分钟', '30分钟', '45分钟', '20分钟', '30分钟'];
  return parsedContent.value.flowSteps.map((_, index) => 
    index < durations.length ? durations[index] : null
  );
});

// 解析须知列表
const noticesList = computed(() => {
  if (!experienceDetail.value.notices) return [];
  
  return experienceDetail.value.notices
    .split('\n')
    .map(item => item.trim())
    .filter(item => item.length > 0);
});

// 获取体验详情
const getExperienceDetail = async () => {
  const experienceId = route.params.id;
  if (!experienceId) {
    ElMessage.error("体验ID不存在");
    router.push('/experiences');
    return;
  }
  
  loading.value = true;
  try {
    // 调用获取体验详情API
    const response = await service.get(`/public/experiences/${experienceId}`);
    
    if (response && response.data && response.data.id) {
      // 后端返回的是{code, message, data}结构，获取data字段
      const detailData = response.data;
      
      // 确保字段名称匹配
      experienceDetail.value = {
        id: detailData.id,
        title: detailData.title,
        category_id: detailData.categoryId, // 注意字段名称转换
        description: detailData.description,
        status: detailData.status,
        duration: detailData.duration,
        maxParticipants: detailData.maxParticipants,
        views: detailData.views,
        price: detailData.price,
        rating: detailData.rating,
        reviewCount: detailData.reviewCount,
        isFavorited: detailData.isFavorited, // 注意字段名称
        images: detailData.images || [],
        content: detailData.content || '',
        notices: detailData.notices || '',
        host: {
          name: detailData.host?.name || '',
          title: detailData.host?.title || '',
          avatar: detailData.host?.avatar || '',
          description: detailData.host?.description || '',
          experienceCount: detailData.host?.experienceCount || 0,
          participantCount: detailData.host?.participantCount || 0,
          rating: detailData.host?.rating || 0
        },
        location: {
          address: detailData.location?.address || '',
          latitude: detailData.location?.latitude,
          longitude: detailData.location?.longitude
        },
        // 保持reviews空数组，等待评价接口单独获取
        reviews: []
      };
      
      // 打印须知信息到控制台
      console.log('体验须知数据:', experienceDetail.value.notices);
      
      // 获取评价数据
      getExperienceReviews();
      
      // 初始化地图
      if (mapLoaded.value && experienceDetail.value.location.address) {
        searchExperienceLocation(experienceDetail.value.title, experienceDetail.value.location.address);
      } else {
        // 延迟初始化地图，确保DOM完全渲染
        setTimeout(() => {
          initMap();
        }, 800);
      }
    }
  } catch (error) {
    console.error("获取体验详情失败:", error);
    ElMessage.error("获取体验详情失败");
  } finally {
    loading.value = false;
  }
};

// 获取体验评价
const getExperienceReviews = async () => {
  const experienceId = route.params.id;
  if (!experienceId) return;
  
  try {
    // 调用获取所有评价API（无分页参数）
    const response = await service.get(`/public/experiences/${experienceId}/reviews`);
    
    if (response && response.data && Array.isArray(response.data)) {
      // 存储所有评价数据
      const allReviews = response.data;
      
      // 前端分页处理
      const startIndex = 0;
      const endIndex = reviewSize.value;
      experienceDetail.value.reviews = allReviews.slice(startIndex, endIndex);
      
      // 判断是否还有更多评价
      hasMoreReviews.value = allReviews.length > reviewSize.value;
      
      // 保存所有评价数据用于本地分页
      allReviewsData.value = allReviews;
    }
  } catch (error) {
    console.error("获取评价失败:", error);
  }
};

// 保存所有评价数据用于本地分页
const allReviewsData = ref([]);

// 加载更多评价（本地分页）
const loadMoreReviews = async () => {
  reviewPage.value += 1;
  
  try {
    // 计算当前应该显示的评价结束索引
    const endIndex = reviewPage.value * reviewSize.value;
    
    // 如果所有评价数据中有足够的数据
    if (allReviewsData.value.length > experienceDetail.value.reviews.length) {
      // 添加下一批评价到当前显示的评价列表中
      const nextBatchReviews = allReviewsData.value.slice(
        experienceDetail.value.reviews.length,
        endIndex
      );
      
      experienceDetail.value.reviews = [
        ...experienceDetail.value.reviews,
        ...nextBatchReviews
      ];
      
      // 更新是否还有更多评价
      hasMoreReviews.value = allReviewsData.value.length > experienceDetail.value.reviews.length;
    } else {
      // 已加载全部评价
      hasMoreReviews.value = false;
    }
  } catch (error) {
    console.error("加载更多评价失败:", error);
    ElMessage.error("加载更多评价失败");
    reviewPage.value -= 1; // 恢复页码
  }
};

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow();
};

// 格式化数字
const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

// 处理收藏
const handleFavorite = async () => {
  const experienceId = route.params.id;
  if (!experienceId) return;
  
  try {
    // 调用收藏API
    const isCurrentlyFavorited = experienceDetail.value.isFavorited;
    const endpoint = `/experiences/favorite/${experienceId}`;
    const method = isCurrentlyFavorited ? 'delete' : 'post';
    
    await service[method](endpoint);
    
    // 更新本地状态
    experienceDetail.value.isFavorited = !isCurrentlyFavorited;
    ElMessage.success(
      experienceDetail.value.isFavorited ? "收藏成功" : "已取消收藏"
    );
  } catch (error) {
    console.error("收藏操作失败:", error);
    ElMessage.error("收藏操作失败，请确保已登录");
  }
};

// 处理分享
const handleShare = () => {
  showShareDialog.value = true;
};

// 处理分享到具体平台
const handleShareTo = (platform) => {
  // 实现具体分享逻辑
  ElMessage.success(`分享到${platform.label}`);
  showShareDialog.value = false;
};

// 复制分享链接
const copyShareUrl = async () => {
  try {
    await navigator.clipboard.writeText(generateShareUrl.value);
    ElMessage.success("链接已复制到剪贴板");
  } catch (err) {
    ElMessage.error("复制失败，请手动复制");
  }
};

// 在 script setup 部分添加以下内容：
const dateShortcuts = [
  {
    text: "今天",
    value: new Date(),
  },
  {
    text: "明天",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() + 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: "一周后",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
      return date;
    },
  },
];

// 禁用日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
};

// 格式化选中日期
const formatSelectedDate = (date) => {
  return dayjs(date).format("YYYY年MM月DD日");
};

// 获取可预订名额
const getAvailableSpots = (day) => {
  // 实现获取可预订名额的逻辑
  return Math.floor(Math.random() * 10);
};

// 处理预订
const handleBook = () => {
  if (!selectedDate.value) {
    ElMessage.warning("请选择体验日期");
    return;
  }

  // 构建订单数据
  const orderData = {
    experienceId: experienceDetail.value.id,
    experienceName: experienceDetail.value.title,
    experienceImage: experienceDetail.value.images[0],
    price: experienceDetail.value.price,
    description: experienceDetail.value.description,
    experienceDate: dayjs(selectedDate.value).format("YYYY-MM-DD"),
    address: experienceDetail.value.location.address,
  };

  router.push({
    path: "/order/confirm",
    query: {
      type: "experience",
      data: encodeURIComponent(JSON.stringify(orderData)),
    },
  });
};

// 增加查询日期可用名额的方法
const getDateAvailability = async (date) => {
  const experienceId = route.params.id;
  if (!experienceId || !date) return;
  
  try {
    const formattedDate = dayjs(date).format('YYYY-MM-DD');
    const response = await service.get(`/public/experiences/${experienceId}/availability`, {
      params: { date: formattedDate }
    });
    
    if (response && response.data && response.data.availableSpots !== undefined) {
      return response.data.availableSpots;
    }
    
    // 如果API没有返回数据，使用随机数
    return Math.floor(Math.random() * 10);
  } catch (error) {
    console.error("获取日期可用名额失败:", error);
    // 出错时使用随机数
    return Math.floor(Math.random() * 10);
  }
};

// 默认提供的服务，按体验类别划分
const defaultServices = {
  // 陶艺类(1)
  1: [
    { name: '专业陶艺师全程指导', icon: 'User' },
    { name: '陶艺工具和材料使用', icon: 'Tools' },
    { name: '作品烧制服务', icon: 'Finished' },
    { name: '成品邮寄服务', icon: 'Van' }
  ],
  // 扎染类(2)
  2: [
    { name: '专业扎染师指导', icon: 'User' },
    { name: '扎染工具与材料', icon: 'Tools' },
    { name: '作品定型处理', icon: 'Finished' },
    { name: '环保染料使用', icon: 'Promotion' }
  ],
  // 美食类(3)
  3: [
    { name: '专业厨师指导', icon: 'User' },
    { name: '食材和烹饪工具', icon: 'Tools' },
    { name: '美食品尝', icon: 'KnifeFork' },
    { name: '食谱分享', icon: 'Document' }
  ],
  // 农事类(4)
  4: [
    { name: '专业农艺指导', icon: 'User' },
    { name: '采摘工具提供', icon: 'Tools' },
    { name: '水果品尝体验', icon: 'Apple' },
    { name: '精美包装服务', icon: 'Box' }
  ],
  // 默认服务
  default: [
    { name: '专业指导服务', icon: 'User' },
    { name: '体验工具与材料', icon: 'Tools' },
    { name: '成品制作服务', icon: 'Finished' },
    { name: '纪念品赠送', icon: 'Present' }
  ]
};

// 加载高德地图脚本
const loadAMapScript = () => {
  return new Promise((resolve, reject) => {
    // 如果AMap已存在且可用，直接返回
    if (window.AMap && typeof window.AMap.Map === 'function') {
      resolve(window.AMap);
      return;
    }
    
    // 清除之前可能存在的脚本，防止冲突
    const existingScript = document.querySelector('script[src*="webapi.amap.com"]');
    if (existingScript) {
      existingScript.parentNode.removeChild(existingScript);
    }
    
    // 重置 AMap 对象，防止使用旧的实例
    if (window.AMap) {
      window.AMap = undefined;
    }
    
    // 确保安全配置已设置
    if (typeof window !== 'undefined' && !window._AMapSecurityConfig) {
      window._AMapSecurityConfig = {
        securityJsCode: securityJsCode
      };
    }
    
    // 添加时间戳防止缓存
    const timestamp = new Date().getTime();
    
    // 创建并加载脚本
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${mapKey}&plugin=AMap.PlaceSearch&t=${timestamp}`;
    
    script.onload = () => {
      resolve(window.AMap);
    };
    
    script.onerror = (error) => {
      reject(new Error('地图加载失败'));
    };
    
    document.head.appendChild(script);
  });
};

// 初始化地图
const initMap = async () => {
  try {
    // 确保地图容器存在
    if (!mapContainer.value || !document.body.contains(mapContainer.value)) {
      setTimeout(() => {
        initMap();
      }, 500);
      return;
    }

    // 确保地图尚未初始化
    if (map) return;

    // 加载高德地图脚本
    await loadAMapScript();

    // 再次确认DOM已经准备好
    if (!mapContainer.value || !document.body.contains(mapContainer.value)) {
      setTimeout(() => {
        initMap();
      }, 300);
      return;
    }

    // 创建地图实例，默认显示贵港市全貌
    map = new AMap.Map(mapContainer.value, {
      zoom: 14,
      center: [109.613196, 23.103333], // 贵港市中心坐标
      resizeEnable: true,
    });

    // 添加标记
    if (experienceDetail.value.location.address) {
      searchExperienceLocation(experienceDetail.value.title, experienceDetail.value.location.address);
    }
    
    mapLoaded.value = true;
  } catch (error) {
    console.error("地图初始化失败:", error);
  }
};

// 搜索体验地点位置并添加标记
const searchExperienceLocation = (title, address) => {
  if (!map || !window.AMap) return;
  
  // 创建地点搜索实例
  const placeSearch = new AMap.PlaceSearch({
    pageSize: 1,
    pageIndex: 1,
    city: '贵港', // 限定城市
    citylimit: true,
  });

  // 优先使用完整地址搜索
  placeSearch.search(address, (status, result) => {
    if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
      // 获取第一个搜索结果的位置
      const position = [
        result.poiList.pois[0].location.lng,
        result.poiList.pois[0].location.lat
      ];
      
      // 添加标记
      addLocationMarker(position, title);
    } else {
      // 如果地址搜索失败，尝试使用体验名称搜索
      placeSearch.search(title, (status, result) => {
        if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
          const position = [
            result.poiList.pois[0].location.lng,
            result.poiList.pois[0].location.lat
          ];
          
          addLocationMarker(position, title);
        } else {
          console.warn("未找到体验地点位置");
        }
      });
    }
  });
};

// 添加地点标记
const addLocationMarker = (position, name) => {
  if (!map) return;
  
  // 清除之前的标记
  map.clearMap();
  
  // 创建标记
  const marker = new AMap.Marker({
    position: position,
    title: name,
    map: map,
    icon: new AMap.Icon({
      size: new AMap.Size(40, 40),
      image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
      imageSize: new AMap.Size(40, 40)
    }),
    offset: new AMap.Pixel(-20, -40)
  });
  
  // 设置地图中心和缩放级别
  map.setCenter(position);
  map.setZoom(15);
  
  // 创建信息窗体
  const infoWindow = new AMap.InfoWindow({
    content: `
      <div style="padding:10px;">
        <h3 style="font-weight:bold;margin-bottom:5px;">${name}</h3>
        <p style="font-size:12px;color:#666;">${experienceDetail.value.location.address}</p>
      </div>
    `,
    offset: new AMap.Pixel(0, -30)
  });
  
  // 点击标记时显示信息窗口
  marker.on('click', () => {
    infoWindow.open(map, marker.getPosition());
  });
  
  // 自动打开信息窗口
  infoWindow.open(map, marker.getPosition());
};

// 清理地图资源
const cleanupMap = () => {
  try {
    // 销毁地图实例
    if (map) {
      map.clearMap();
      map.destroy();
      map = null;
    }
    
    mapLoaded.value = false;
  } catch (error) {
    console.warn("清理地图资源时发生错误:", error);
  }
};

// 页面加载时获取数据
onMounted(async () => {
  getExperienceDetail();
  getExperienceReviews();
  
  // 确保安全配置已设置
  if (typeof window !== 'undefined') {
    window._AMapSecurityConfig = {
      securityJsCode: securityJsCode
    };
  }
  
  // 确保DOM已更新
  await nextTick();
  
  // 延迟初始化，确保DOM完全渲染
  setTimeout(() => {
    initMap();
  }, 800);
});

onBeforeUnmount(() => {
  cleanupMap();
});
</script>

<style lang="scss" scoped>
.experience-detail-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  :deep(.el-carousel) {
    .el-carousel__container {
      @apply rounded-lg;
    }

    .el-carousel__item {
      .el-image {
        @apply w-full h-full;
      }
    }
  }

  :deep(.el-calendar) {
    --el-calendar-cell-width: 42px;

    .calendar-cell {
      @apply flex flex-col items-center justify-center h-full;

      .is-selected {
        @apply bg-primary-500 text-white rounded-full w-7 h-7 flex items-center justify-center;
      }

      .available-spots {
        @apply text-xs text-primary-600 dark:text-primary-400 mt-1;
      }
    }
  }

  :deep(.el-rate) {
    .el-rate__icon {
      &.el-icon {
        @apply text-yellow-400 dark:text-yellow-500;
      }
    }
  }

  .prose {
    @apply text-gray-700 dark:text-gray-300;

    h2 {
      @apply text-xl font-bold text-gray-900 dark:text-white my-4;
    }

    p {
      @apply mb-4 leading-relaxed;
    }

    ul,
    ol {
      @apply mb-4 space-y-2;
    }

    li {
      @apply ml-4;
    }
  }

  .review-item {
    @apply border-b border-gray-100 dark:border-gray-700 pb-6;
    &:last-child {
      @apply border-b-0 pb-0;
    }
  }
}
</style>
